<?php
//Include all classes and the design
require '../classes/includeAll.php';
$titel="Upload - Devices";
$head='<link rel="stylesheet" type="text/css" href="../design/css/upload.css">';
require '../menu/head.php';

require '../resources/getConnection.php';
require_once '../resources/phpFunctions.php';

//Content
$sent=false;

if(isset($_POST['submit'])){                 //Routine wenn hinzufügen geklickt wurde
    $sent=true;
    
    if($_FILES['datei'] == ''){                //überprüft die Datei
    }  
    else{   //Überprüft ob das richtige Format vorhanden ist 
        $allowed_types = "csv";	// Erlaubte Dateitypen
        if(preg_match("/\." . $allowed_types . "$/i", $_FILES["datei"]["name"])){
           $data = $_FILES['datei']['name'];
        }
        else{ 
        }
    }
    
    $table =  fopen($_FILES["datei"]["tmp_name"],'r');
    
    $firstLine = TRUE;
    
    $uploadDevices = new Devices($connection);  //get all existing devices
    $devices = $uploadDevices->getAllDevices();

    $tempDevice = new Device(NULL,$connection); //temporary device to upload into the DB

    $queries = new mysqlqueries();

    $devicesId = array();
    $devicesName = array();
    $devicesMac = array();

    $log=array();
    
    foreach ($devices as $device) { //The Arrays containing the information of existing devices are created
        $device->getInfrastructure();
        array_push($devicesId, $device->ID);
        array_push($devicesName, strtolower($device->Name));
        array_push($devicesMac, strtolower($device->Mac));
    }

    while($csvLine=fgetcsv($table,1024,';')){
        if($firstLine){
            $firstLine = FALSE;
        }
        else {
            $tempDevice->Name = trim(utf8_encode($csvLine[0]));
            $tempDevice->Mac = trim(utf8_encode($csvLine[2]));     //on this values is decided if an existing device gets updated or a new one is created

            $tempDevice->InventoryNumber = trim(utf8_encode($csvLine[3]));
            $tempDevice->SerialNumber = trim(utf8_encode($csvLine[4]));
            $tempDevice->PurchaseDate = trim(utf8_encode(ConvertDate($csvLine[5], FALSE)));
            $tempDevice->Warranty = trim(utf8_encode($csvLine[6]));
            $tempDevice->Note = trim(utf8_encode($csvLine[7]));
            $tempDevice->Manufacturer = trim(utf8_encode($csvLine[8])); //these values do not matter when deciding what to do next
            $tempDevice->RoomShould = trim(utf8_encode($csvLine[10]));
            $tempDevice->LevelShould  = trim(utf8_encode($csvLine[11]));
            
            $tempSupplier=new Suppliers($connection);
            $tempSupplier->name = trim(utf8_encode($csvLine[9]));
            if($tempSupplier->name==""){$tempSupplier->name="unknown";}
            $tempDeviceType = new DeviceTypes($connection);
            $tempDeviceType->description = trim(utf8_encode($csvLine[1])); //the devicetype and supplier are stored in sepperate tables, this is why they are treated different

            $tempDevice->DeviceTypeID=trim(utf8_encode($tempDeviceType->ExistsOrCreate()));
            $tempDevice->SupplierID=trim(utf8_encode($tempSupplier->ExistsOrCreate())); //if the supplier or the device type do not exist at the moment a new table entry will be created

            if($tempDevice->Mac!=""){
                if(in_array(strtolower($tempDevice->Mac), $devicesMac))
                { 
                    if(in_array(strtolower($tempDevice->Name), $devicesName)){ 
                        if(array_search(strtolower($tempDevice->Mac), $devicesMac) ==  array_search(strtolower($tempDevice->Name), $devicesName)){ //is it used for the same device?
                            $tempDevice->UpdateFromCsvMac();
                            array_push($log, "Das Gerät <a href=device.php?dev=$tempDevice->ID target=\"_blank\">$tempDevice->Name</a> wurde geändert.");
                        }
                        else{
                            $tempDevice->UpdateFromCsvMac();
                            array_push($log, "Das geänderte Gerät mit dem Namen <a href=device.php?dev=$tempDevice->ID target=\"_blank\">$tempDevice->Name</a> hat den selben Namen wie ein bereits existierendes Gerät.");
                        }
                    }//is this device name already used?
                    else {
                        $tempDevice->UpdateFromCsvMac();
                        array_push($log, "Das Gerät <a href=device.php?dev=$tempDevice->ID target=\"_blank\">$tempDevice->Name</a> wurde geändert.");
                    }
                }//is the MAC already in the DB?
                else{
                    if(in_array(strtolower($tempDevice->Name), $devicesName)){
                        $tempDevice->UpdateFromCsvName();
                        array_push($log, "Mac Adresse des Gerätes <a href=device.php?dev=$tempDevice->ID target=\"_blank\">$tempDevice->Name</a> wurde geändert. Achtung dieses Gerät könnte nun mehrere Mac Adressen besitzen."); 
                    }
                    else {
                        $tempDevice->CreateFromCsv();
                        array_push($log, "Gerät <a href=device.php?dev=$tempDevice->ID target=\"_blank\">$tempDevice->Name</a> wurde erstellt.");
                    }
                   
                    $tempDevice->AddMac();
                }
            }
            else{
                if(in_array(strtolower($tempDevice->Name),$devicesName)){
                    $tempDevice->UpdateFromCsvName();
                    array_push($log, "Mac Adresse des Gerätes <a href=device.php?dev=$tempDevice->ID target=\"_blank\">$tempDevice->Name</a> wurde geändert. Achtung dieses Gerät könnte nun mehrere Mac Adressen besitzen."); 
                }
                else {
                    $tempDevice->CreateFromCsv();
                    array_push($log, "Gerät <a href=device.php?dev=$tempDevice->ID target=\"_blank\">$tempDevice->Name</a> wurde erstellt.");
                }
            }
            if($tempDevice->RoomShould!=""){
            #get should room number an id
            $tempRoom=new roomAndLevel($connection);    #create new room for the ExistsOrCreate() function
            $tempRoom->RoomNumber=$tempDevice->RoomShould;    #assign the room name 
            $tempRoom->LevelName=$tempDevice->LevelShould;  #assign the level
            $tempRoomSQL = $connection->query($queries->GetIndex($queries->Room, $tempDevice->RoomShould, 'number', null));
            if($tempRoomDB = mysqli_fetch_array($tempRoomSQL)){
                $tempRoom->RoomID = $tempRoomDB['ID'];
                $tempRoom->RoomName = $tempRoomDB['name'];
            }
            
            $tempRoom->RoomExistsOrCreate(TRUE);
                            
            $tempRelocations=$connection->query($queries->AddLimit($queries->GetIndex($queries->Relocation, $tempDevice->ID, 'device_ID', 'ID DESC'),0,1));

            $exists=false;
            
            while($tempRelocation = mysqli_fetch_array($tempRelocations)){
                $exists=true;
                $argument=array(NULL,  ConvertDateTimeToDate(NULL, false), $tempDevice->ID, $tempRelocation['roomIs_ID'], $tempRoom->RoomID);
                $connection->query($queries->Add($queries->Relocation, $argument));
            }
            if(!$exists){
                $argument=array(NULL,  ConvertDateTimeToDate(NULL, false), $tempDevice->ID, NULL, $tempRoom->RoomID);
                $connection->query($queries->Add($queries->Relocation, $argument));
            }
            }
        }
    }
    
    echo"<h1>Ereignislog:</h1></br>";
    foreach ($log as $logentry){
        echo"$logentry</br>";
    }
    
}
if(!$sent){
    echo '<div id="contentLeft">';
    echo "<div id=\"textbox\">"
    . "Diese Seite ermöglicht es Ihnen, eine Liste von Geräten in die Datenbank zu laden. Hierzu steht eine Vorlage zum Download bereit. Die Vorlage kann mit einem beliebigen Tabellenkalkulationsprogramm oder einem Texteditor bearbeitet werden. Die erste Zeile muss erhalten bleiben. Die Mac-Adressen müssen im Format xx-xx-xx-xx-xx-xx eingetragen werden.</br>"
    . "</br><input type=\"button\" value=\"Download\" onclick=\"window.open('../resources/vorlage_device.csv')\"></input>"
    . "</div></div>";
    
    echo"
    <div id=\"contentRight\">
    <form action=\"../pages/upload.php\" method=\"post\" enctype=\"multipart/form-data\">
    <span>W&auml;hlen Sie eine CSV-Datei von Ihrem Rechner aus (max. 2MB):<br>
    <input name=\"datei\" type=\"file\" size=\"50\" maxlength=\"262144\" accept=\".csv\"><br>
    <input type=\"submit\" value=\"submit\" name=\"submit\" /></span>
    </form></div>";
}


require '../menu/footer.php';
?>
